package com.wanxi.config;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//代表过滤所有访问后台的接口
public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        /**
         * 1.得到访问后台的接口地址
         * 2.判断哪些地址可以访问
         * 3.放行：如果可以访问则放行，如果不能访问，则跳转到登录页面
         */
        String path = req.getServletPath();
        System.out.println(path);
//        只要以back开头的都必须进行登录，否则直接放行
        if (path.startsWith("/back/")) {
            String username = (String) req.getSession().getAttribute("username");
            if (username == null) {
                res.sendRedirect("/html/login.html");
            } else {
                //            放行
                chain.doFilter(req, res);
            }

        } else {
            //            放行
            chain.doFilter(req, res);
        }

    }
}
